from masonite.middleware import Middleware
from masonite.facades import (Session, Cache)
from app.traits.MyModelTrait import MyModelTrait


class AdminUserTokenMiddleware(Middleware):
    def before(self, request, response):
        if not Session.has('admin_user'):
            return response.redirect("/admin/user/login", status=302)
        key = MyModelTrait.generate_cache_key(Session.get('admin_user')['id'])
        if Cache.get(key) != Session.get('admin_user')['token']:
            return response.redirect("/admin/user/login", status=302)
        return request

    def after(self, request, response):
        return request
